import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 应用其他状态
  },
  getters: {
    // 可以提供一些辅助的getter函数，但不再存储token相关信息
    isLoggedIn: () => !!localStorage.getItem('token'),
    userInfo: () => {
      const userInfoStr = localStorage.getItem('userInfo')
      return userInfoStr ? JSON.parse(userInfoStr) : {}
    },
    token: () => localStorage.getItem('token')
  },
  mutations: {
    // 其他应用状态的mutations
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        // 假设这里调用了登录接口
        setTimeout(() => {
          const { username, password } = userInfo
          if (username === 'admin' && password === 'admin') {
            const token = 'mock-token-' + Math.random().toString(36).substr(2)
            const userInfo = { username, role: 'admin' }
            commit('SET_TOKEN', token)
            commit('SET_USER_INFO', userInfo)
            resolve()
          } else {
            reject(new Error('用户名或密码错误'))
          }
        }, 300)
      })
    },
    // 登出操作，直接操作localStorage
    logout() {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      return Promise.resolve()
    }
  },
  modules: {
  }
}) 